import * as ffmpeg from "fluent-ffmpeg"
import * as path from "path"

/**
 * 生成视频缩略图
 * @param videoPath 视频路径
 * @param savePath 生成文件保存路径
 */
export const generateVideoThumbnail = (videoPath: string, format: string) => {
    return new Promise<string>((reslove, reject) => {
        try {

            var extname = path.extname(videoPath);
            var savePath = videoPath.replace(extname,format);
            ffmpeg(videoPath)
                .seekInput('00:00:02') // 设置从视频的第2秒开始
                .frames(1)             // 抓取一帧作为缩略图
                .size('320x240')       // 设置缩略图的尺寸为320x240
                .on('end', () => {
                    // console.log('缩略图生成成功！');
                    reslove(savePath);
                })
                .on('error', err => {
                    // console.log('生成缩略图时出错：', err);
                    reslove('');
                })
                .save(savePath);
        } catch (err) {
            reject(err);
        }
    })
}

// 暂时没有测试
const captureImageOne = (src) => {
    return new Promise((reslove, reject) => {
        try {
            let imageName = '';
            let fileName = src.substring(src.lastIndexOf('/') + 1).split(".")[0];
            ffmpeg(src)
                .on('filenames', (filenames) => {
                    imageName = filenames[0];
                    console.log(imageName);
                })
                .on('end', () => {
                    reslove(imageName);
                })
                .screenshots({
                    // Will take screens at 20%, 40%, 60% and 80% of the video
                    //timestamps: [30.5, '50%', '01:10.123'],
                    timestamps: ['00:01.000'],
                    folder: './dist/upload/img/',
                    filename: fileName + '.png',
                });
        } catch (err) {
            reject(err);
        }
    })
}
